//
//  RZVideoCaptureViewController.m
//  RZIM
//
//  Created by reyzhang on 2021/8/26.
//

#import "RZVideoCaptureViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "RZRecordButton.h"
#import "RZAVPlayer.h"
#import "RZIMDefine.h"
#import "XFPhotoLibraryManager.h"
#import "RZKitCommonDefine.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "UIManager.h"


typedef void(^PropertyChangeBlock)(AVCaptureDevice *captureDevice);

@interface RZVideoCaptureViewController ()<AVCaptureFileOutputRecordingDelegate,RZRecordButtonDelegate>
//视频输出流
@property (strong,nonatomic) AVCaptureMovieFileOutput *captureMovieFileOutput;
//图片输出流
//@property (strong,nonatomic) AVCaptureStillImageOutput *captureStillImageOutput;//照片输出流
//负责从AVCaptureDevice获得输入数据
@property (strong,nonatomic) AVCaptureDeviceInput *captureDeviceInput;
//后台任务标识
@property (assign,nonatomic) UIBackgroundTaskIdentifier backgroundTaskIdentifier;

@property (assign,nonatomic) UIBackgroundTaskIdentifier lastBackgroundTaskIdentifier;

@property (weak, nonatomic) IBOutlet UIImageView *focusCursor; //聚焦光标
//是否是摄像 YES 代表是录制  NO 表示拍照
@property (assign, nonatomic) BOOL isVideo;
//负责输入和输出设备之间的数据传递
@property(nonatomic)AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;

@property (strong, nonatomic) IBOutlet UIButton *btnBack;
//重新录制
@property (strong, nonatomic) IBOutlet UIButton *btnAfresh;
//确定
@property (strong, nonatomic) IBOutlet UIButton *btnEnsure;
//摄像头切换
@property (strong, nonatomic) IBOutlet UIButton *btnCamera;

@property (strong, nonatomic) IBOutlet UIImageView *bgView;
//记录录制的时间 默认最大60秒
@property (assign, nonatomic) NSInteger seconds;

//记录需要保存视频的路径
@property (strong, nonatomic) NSURL *saveVideoUrl;

//是否在对焦
@property (assign, nonatomic) BOOL isFocus;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *afreshCenterX;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *ensureCenterX;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *backCenterX;

//视频播放
@property (strong, nonatomic) RZAVPlayer *player;

@property (strong, nonatomic) UIImage *takeImage;

@property (strong, nonatomic) UIImageView *takeImageView;

@property(nonatomic, strong)  RZRecordButton *recordBtn; // 录像按钮

@property(nonatomic, assign)BOOL isSystemEndRecord; // 记录系统是否成功结束了录制
@end

//时间大于这个就是视频，否则为拍照
#define TimeMax 0.5

@implementation RZVideoCaptureViewController

+ (instancetype)sharedVideoVC {
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"RZIM" ofType:@"bundle"]];
    RZVideoCaptureViewController *ctrl = [[RZVideoCaptureViewController alloc] initWithNibName:@"RZVideoCaptureViewController" bundle:bundle];
//    RZVideoCaptureViewController *ctrl = [[RZVideoCaptureViewController alloc] initWithNibName:@"RZVideoCaptureViewController" bundle:nil];
    ctrl.view.frame = [UIScreen mainScreen].bounds;
    ctrl.HSeconds = 30;//设置可录制最长时间
    ctrl.mediaType = SelectMediaTypeBoth;
    ctrl.labelTipTitle.text = @"轻触拍照，按住摄像";
    return ctrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *image = [UIImage imageNamed:@"sc_btn_take.png"];
    self.backCenterX.constant = -(SCREEN_WIDTH / 2 / 2) - image.size.width / 2 / 2;
    
    _recordBtn         = [RZRecordButton buttonWithType:UIButtonTypeCustom];
    CGFloat width      = 70.f;
    CGRect frame = CGRectMake((SCREEN_WIDTH -  width)/2, [UIScreen mainScreen].bounds.size.height - width - kSafeAreaBottom - 60 , width, width);

    _recordBtn.frame  =  frame;
    _recordBtn.rz_delegate = self;
    [_recordBtn addTarget:self action:@selector(rz_startRecording:) forControlEvents:UIControlEventTouchDown];
    [_recordBtn addTarget:self action:@selector(rz_endRecord:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_recordBtn];
    
    [self.btnBack setImage:RZResourceImage(@"hVideo_back") forState:UIControlStateNormal];
    [self.btnCamera setImage:RZResourceImage(@"btn_video_flip_camera") forState:UIControlStateNormal];
    [self.btnAfresh setImage:RZResourceImage(@"hVideo_cancel") forState:UIControlStateNormal];
    [self.btnEnsure setImage:RZResourceImage(@"hVideo_confirm") forState:UIControlStateNormal];
    
    
    [self performSelector:@selector(hiddenTipsLabel) withObject:nil afterDelay:4];
}

- (void)rz_startRecording:(RZRecordButton *)button
{
    _isSystemEndRecord = NO;
    [button rz_startRecording:^(BOOL finish, BOOL isEndRecord) {
        //    NSLog(@"%d -- %d", isEndRecord, self.isSystemEndRecord);
        if (isEndRecord && !self.isSystemEndRecord) { // 抬起了按钮，并且系统未成功开始录制（未走录制成功的代理方法）
            self.btnCamera.hidden = NO;
            self.btnBack.hidden = NO;
            AVCaptureConnection *captureConnection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
            captureConnection.videoOrientation = [self->_previewLayer connection].videoOrientation;
            [self.captureMovieFileOutput startRecordingToOutputFileURL:({
                NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.mp4"]];
                if ([[NSFileManager defaultManager] fileExistsAtPath:url.path]) {
//                    [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
                }
                self.isVideo = NO;
                url;
            }) recordingDelegate:self];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if ([self.captureMovieFileOutput isRecording]) {
                    [self.captureMovieFileOutput stopRecording];
                }
            });
        } else if (!isEndRecord) { // 动画执行完毕并且未抬起按钮结束录制
            if (![self.captureMovieFileOutput isRecording]) {
                self.btnBack.hidden = YES;
                self.btnCamera.hidden = YES;
                NSLog(@"开始录制视频...");
                AVCaptureConnection *captureConnection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
                captureConnection.videoOrientation = [self->_previewLayer connection].videoOrientation;
                [self.captureMovieFileOutput startRecordingToOutputFileURL:({
                    NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.mp4"]];
                    if ([[NSFileManager defaultManager] fileExistsAtPath: url.path]) {
                        [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
                    }
                    self.isVideo = YES;
                    url;
                }) recordingDelegate:self];
            } else {
                // 视频录制中，不要做任何操作
                return;
            }
        }
    }];
}


#pragma mark - RZRecordButtonDelegate --用户未主动抬起按钮，倒计时结束
- (void)rz_delegateEndCountdown
{
    [self rz_endRecord:_recordBtn];
}

- (void)rz_endRecord:(RZRecordButton *)button
{
    [button rz_endRecord];
    if ([self.captureMovieFileOutput isRecording]) {
        [self.captureMovieFileOutput stopRecording]; // 通过代理实现结束之后的操作
    }
}
- (void)hiddenTipsLabel
{
    self.labelTipTitle.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)
    {
        [XFPhotoLibraryManager requestAuthorizationForVideoWithVC:self];
    }
    
    //判断用户是否允许访问麦克风权限
    authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)
    {
        [XFPhotoLibraryManager requestAuthorizationForVideoWithVC:self];
    }
    [XFPhotoLibraryManager requestAuthorizationForPhotoLibraryWithVC:self];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [self customCamera];
    [self.session startRunning];
}


-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.session stopRunning];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)customCamera
{
    //初始化会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc] init];
    //设置分辨率 (设备支持的最高分辨率)
    if ([self.session canSetSessionPreset:AVCaptureSessionPresetHigh]) {
        self.session.sessionPreset = AVCaptureSessionPresetHigh;
    }
    //取得后置摄像头
    AVCaptureDevice *captureDevice = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];
    //添加一个音频输入设备
    AVCaptureDevice *audioCaptureDevice=[[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
    //初始化输入设备
    NSError *error = nil;
    self.captureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:captureDevice error:&error];
    if (error) {
        NSLog(@"取得设备输入对象时出错，错误原因：%@",error.localizedDescription);
        return;
    }
    //添加音频
    error = nil;
    AVCaptureDeviceInput *audioCaptureDeviceInput=[[AVCaptureDeviceInput alloc]initWithDevice:audioCaptureDevice error:&error];
    if (error) {
        NSLog(@"取得设备输入对象时出错，错误原因：%@",error.localizedDescription);
        return;
    }
    //输出对象
    self.captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];//视频输出
    //将输入设备添加到会话
    if ([self.session canAddInput:self.captureDeviceInput]) {
        [self.session addInput:self.captureDeviceInput];
        [self.session addInput:audioCaptureDeviceInput];
        //设置视频防抖
        AVCaptureConnection *connection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
        if ([connection isVideoStabilizationSupported]) {
            connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeCinematic;
        }
    }
    
    //将输出设备添加到会话 (刚开始 是照片为输出对象)
    if ([self.session canAddOutput:self.captureMovieFileOutput]) {
        [self.session addOutput:self.captureMovieFileOutput];
    }
    
    //创建视频预览层，用于实时展示摄像头状态
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0,SCREEN_WIDTH, SCREEN_HEIGHT);//self.view.bounds; self.view.width
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//填充模式
    [self.bgView.layer addSublayer:self.previewLayer];
    
    [self addNotificationToCaptureDevice:captureDevice];
    [self addGenstureRecognizer];
}

- (IBAction)onCancelAction:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        //[Utility hideProgressDialog];
    }];
}


- (void)endRecord
{
    [self.captureMovieFileOutput stopRecording];//停止录制
}

- (IBAction)onAfreshAction:(UIButton *)sender
{
    [self.player stopPlayer];
    NSLog(@"重新录制");
    [self recoverLayout];
}

- (IBAction)onEnsureAction:(UIButton *)sender {
    NSLog(@"确定 这里进行保存或者发送出去");
    [self.player startAnimation];
    if (self.saveVideoUrl) {
        sender.userInteractionEnabled = NO;
        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
        [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:self.saveVideoUrl completionBlock:^(NSURL *assetURL, NSError *error) {
            NSLog(@"outputUrl:%@",self.saveVideoUrl);
//            [[NSFileManager defaultManager] removeItemAtURL:self.saveVideoUrl error:nil];
            if (error) {
                NSLog(@"保存视频到相簿过程中发生错误，错误信息：%@",error.localizedDescription);
            } else {
                NSLog(@"成功保存视频到相簿.");
                if (self.takeBlock) {
                    self.takeBlock(SelectMediaTypeVideo,assetURL);
                }
                [self onCancelAction:nil];
            }
            [self.player stopAnimation];
            sender.userInteractionEnabled = YES;
        }];
    }else{// 照片
        __block ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
        [lib writeImageToSavedPhotosAlbum:self.takeImage.CGImage metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
            self.assetURL = assetURL;
            if (!error) {
                if (self.takeBlock) {
                    self.takeBlock(SelectMediaTypePhoto,self.takeImage);
                }
                [self onCancelAction:nil];
            }
            NSLog(@"assetURL = %@, error = %@  image = %@", assetURL, error,self.takeImage);
            lib = nil;
        }];
    }
}

//前后摄像头的切换
- (IBAction)onCameraAction:(UIButton *)sender
{
    NSLog(@"切换摄像头");
    AVCaptureDevice *currentDevice=[self.captureDeviceInput device];
    AVCaptureDevicePosition currentPosition=[currentDevice position];
    [self removeNotificationFromCaptureDevice:currentDevice];
    AVCaptureDevice *toChangeDevice;
    AVCaptureDevicePosition toChangePosition = AVCaptureDevicePositionFront;//前
    if (currentPosition == AVCaptureDevicePositionUnspecified || currentPosition == AVCaptureDevicePositionFront) {
        toChangePosition = AVCaptureDevicePositionBack;//后
    }
    toChangeDevice = [self getCameraDeviceWithPosition:toChangePosition];
    [self addNotificationToCaptureDevice:toChangeDevice];
    //获得要调整的设备输入对象
    AVCaptureDeviceInput *toChangeDeviceInput=[[AVCaptureDeviceInput alloc]initWithDevice:toChangeDevice error:nil];
    //改变会话的配置前一定要先开启配置，配置完成后提交配置改变
    [self.session beginConfiguration];
    //移除原有输入对象
    [self.session removeInput:self.captureDeviceInput];
    //添加新的输入对象
    if ([self.session canAddInput:toChangeDeviceInput]) {
        [self.session addInput:toChangeDeviceInput];
        self.captureDeviceInput = toChangeDeviceInput;
    }
    //提交会话配置
    [self.session commitConfiguration];
}

-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
    NSLog(@"视频录制完成.");
    self.isSystemEndRecord = YES;
    [self changeLayout];
    if (self.isVideo) {
        self.saveVideoUrl = outputFileURL;
        if (!self.player) {
            self.player = [[RZAVPlayer alloc] initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) withShowInView:self.bgView url:outputFileURL];
        } else {
            if (outputFileURL) {
                self.player.videoUrl = outputFileURL;
                self.player.hidden = NO;
            }
        }
    }else{
        // 照片
        self.saveVideoUrl = nil;
        [self videoHandlePhoto:outputFileURL];
    }
}

- (void)videoHandlePhoto:(NSURL *)url
{
    AVURLAsset *urlSet = [AVURLAsset assetWithURL:url];
    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
    imageGenerator.appliesPreferredTrackTransform = YES;    // 截图的时候调整到正确的方向
    NSError *error = nil;
    CMTime time = CMTimeMake(0,6000);//缩略图创建时间 CMTime是表示电影时间信息的结构体，第一个参数表示是视频第几秒，第二个参数表示每秒帧数.(如果要获取某一秒的第几帧可以使用CMTimeMake方法)
    CMTime actucalTime; //缩略图实际生成的时间
    CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:&actucalTime error:&error];
    UIImage *image;
    
    if (error) {
        NSLog(@"截取视频图片失败:%@",error.localizedDescription);
        image = [UIImage imageNamed:@"photo_placeholder"];
    }else{
        image = [UIImage imageWithCGImage:cgImage];
    }
    CMTimeShow(actucalTime);
    CGImageRelease(cgImage);
    if (image) {
        NSLog(@"视频截取成功");
    } else {
        NSLog(@"视频截取失败");
    }
    self.takeImage = image;//[UIImage imageWithCGImage:cgImage];
    [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
    if (!self.takeImageView) {
        self.takeImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
        [self.bgView addSubview:self.takeImageView];
    }
    self.takeImageView.hidden = NO;
    self.takeImageView.image = self.takeImage;
}

#pragma mark - 通知

//注册通知
- (void)setupObservers
{
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationWillResignActiveNotification object:[UIApplication sharedApplication]];
}

//进入后台就退出视频录制
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [self onCancelAction:nil];
}

/**
 *  给输入设备添加通知
 */
-(void)addNotificationToCaptureDevice:(AVCaptureDevice *)captureDevice{
    //注意添加区域改变捕获通知必须首先设置设备允许捕获
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        captureDevice.subjectAreaChangeMonitoringEnabled=YES;
    }];
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    //捕获区域发生改变
    [notificationCenter addObserver:self selector:@selector(areaChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice];
}
-(void)removeNotificationFromCaptureDevice:(AVCaptureDevice *)captureDevice
{
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice];
}
/**
 *  移除所有通知
 */
-(void)removeNotification
{
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self];
}

-(void)addNotificationToCaptureSession:(AVCaptureSession *)captureSession
{
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    //会话出错
    [notificationCenter addObserver:self selector:@selector(sessionRuntimeError:) name:AVCaptureSessionRuntimeErrorNotification object:captureSession];
}

/**
 *  设备连接成功
 *
 *  @param notification 通知对象
 */
-(void)deviceConnected:(NSNotification *)notification
{
    NSLog(@"设备已连接...");
}
/**
 *  设备连接断开
 *
 *  @param notification 通知对象
 */
-(void)deviceDisconnected:(NSNotification *)notification
{
    NSLog(@"设备已断开.");
}
/**
 *  捕获区域改变
 *
 *  @param notification 通知对象
 */
-(void)areaChange:(NSNotification *)notification
{
    NSLog(@"捕获区域改变...");
}

/**
 *  会话出错
 *
 *  @param notification 通知对象
 */
-(void)sessionRuntimeError:(NSNotification *)notification
{
    NSLog(@"会话发生错误.");
}



/**
 *  取得指定位置的摄像头
 *
 *  @param position 摄像头位置
 *
 *  @return 摄像头设备
 */
-(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position
{
    NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if ([camera position] == position) {
            return camera;
        }
    }
    return nil;
}
/**
 *  改变设备属性的统一操作方法
 *
 *  @param propertyChange 属性改变操作
 */
-(void)changeDeviceProperty:(PropertyChangeBlock)propertyChange
{
    AVCaptureDevice *captureDevice= [self.captureDeviceInput device];
    NSError *error;
    //注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁
    if ([captureDevice lockForConfiguration:&error]) {
        //自动白平衡
        if ([captureDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
            [captureDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance];
        }
        //自动根据环境条件开启闪光灯
        if ([captureDevice isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [captureDevice setFlashMode:AVCaptureFlashModeAuto];
        }
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
    }else{
        NSLog(@"设置设备属性过程发生错误，错误信息：%@",error.localizedDescription);
    }
}

/**
 *  设置闪光灯模式
 *
 *  @param flashMode 闪光灯模式
 */
-(void)setFlashMode:(AVCaptureFlashMode )flashMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isFlashModeSupported:flashMode]) {
            [captureDevice setFlashMode:flashMode];
        }
    }];
}
/**
 *  设置聚焦模式
 *
 *  @param focusMode 聚焦模式
 */
-(void)setFocusMode:(AVCaptureFocusMode )focusMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isFocusModeSupported:focusMode]) {
            [captureDevice setFocusMode:focusMode];
        }
    }];
}
/**
 *  设置曝光模式
 *
 *  @param exposureMode 曝光模式
 */
-(void)setExposureMode:(AVCaptureExposureMode)exposureMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isExposureModeSupported:exposureMode]) {
            [captureDevice setExposureMode:exposureMode];
        }
    }];
}
/**
 *  设置聚焦点
 *
 *  @param point 聚焦点
 */
-(void)focusWithMode:(AVCaptureFocusMode)focusMode exposureMode:(AVCaptureExposureMode)exposureMode atPoint:(CGPoint)point{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isExposureModeSupported:exposureMode]) {
            [captureDevice setExposureMode:exposureMode];
        }
        if ([captureDevice isFocusModeSupported:focusMode]) {
            [captureDevice setFocusMode:focusMode];
        }
    }];
}

/**
 *  添加点按手势，点按时聚焦
 */
-(void)addGenstureRecognizer{
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapScreen:)];
    [self.bgView addGestureRecognizer:tapGesture];
}

-(void)tapScreen:(UITapGestureRecognizer *)tapGesture{
    if ([self.session isRunning]) {
        CGPoint point= [tapGesture locationInView:self.bgView];
        //将UI坐标转化为摄像头坐标
        CGPoint cameraPoint= [self.previewLayer captureDevicePointOfInterestForPoint:point];
        [self setFocusCursorWithPoint:point];
        [self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposureMode:AVCaptureExposureModeContinuousAutoExposure atPoint:cameraPoint];
    }
}

/**
 *  设置聚焦光标位置
 *
 *  @param point 光标位置
 */
-(void)setFocusCursorWithPoint:(CGPoint)point{
    if (!self.isFocus) {
        self.isFocus = YES;
        self.focusCursor.center=point;
        self.focusCursor.transform = CGAffineTransformMakeScale(1.25, 1.25);
        self.focusCursor.alpha = 1.0;
        [UIView animateWithDuration:0.5 animations:^{
            self.focusCursor.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self performSelector:@selector(onHiddenFocusCurSorAction) withObject:nil afterDelay:0.5];
        }];
    }
}

- (void)onHiddenFocusCurSorAction
{
    self.focusCursor.alpha=0;
    self.isFocus = NO;
}

//拍摄完成时调用
- (void)changeLayout
{
    self.btnCamera.hidden = YES;
    self.btnAfresh.hidden = NO;
    self.btnEnsure.hidden = NO;
    self.btnBack.hidden   = YES;
    self.recordBtn.hidden = YES;
    self.afreshCenterX.constant = -(SCREEN_WIDTH / 2 /2);
    self.ensureCenterX.constant = SCREEN_WIDTH / 2 / 2;
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    [self.session stopRunning];
}


//重新拍摄时调用
- (void)recoverLayout
{
    [self.session startRunning];
    if (self.isVideo){
        self.isVideo = NO;
        self.player.hidden = YES;
        [self.player stopPlayer];
    }
    
    if (!self.takeImageView.hidden) {
        self.takeImageView.hidden = YES;
    }
    self.saveVideoUrl           = nil;
    self.afreshCenterX.constant = 0;
    self.ensureCenterX.constant = 0;
    self.recordBtn.hidden = NO;
    self.btnCamera.hidden = NO;
    self.btnAfresh.hidden = YES;
    self.btnEnsure.hidden = YES;
    self.btnBack.hidden   = NO;
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
        
    }];
}

-(void)dealloc
{
    [self removeNotification];
}
@end
